const { Pool } = require('pg');
require('dotenv').config();

// PostgreSQL 数据库配置
const pool = new Pool({
  user: process.env.POSTGRES_USER || 'rwa_user',
  host: process.env.POSTGRES_HOST || 'localhost',
  database: process.env.POSTGRES_DB || 'rwa_contract',
  password: process.env.POSTGRES_PASSWORD || 'rwa_password',
  port: process.env.POSTGRES_PORT || 5432,
  max: 20, // 最大连接数
  idleTimeoutMillis: 30000, // 空闲连接超时时间
  connectionTimeoutMillis: 2000, // 连接超时时间
});

// 测试数据库连接
pool.on('connect', () => {
  console.log('✅ Connected to PostgreSQL database');
});

pool.on('error', (err) => {
  console.error('❌ PostgreSQL connection error:', err);
  process.exit(-1);
});

// 初始化数据库表
const initDatabase = async () => {
  try {
    const client = await pool.connect();
    
    // 创建代币表
    await client.query(`
      CREATE TABLE IF NOT EXISTS tokens (
        id SERIAL PRIMARY KEY,
        address VARCHAR(42) UNIQUE NOT NULL,
        name VARCHAR(255) NOT NULL,
        symbol VARCHAR(10) NOT NULL,
        decimals INTEGER NOT NULL,
        total_supply VARCHAR(78) NOT NULL,
        owner_address VARCHAR(42) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);
    
    // 创建销售计划表
    await client.query(`
      CREATE TABLE IF NOT EXISTS sale_plans (
        id SERIAL PRIMARY KEY,
        token_address VARCHAR(42) NOT NULL UNIQUE,
        total_tokens VARCHAR(78) NOT NULL,
        price VARCHAR(78) NOT NULL,
        validity_period INTEGER NOT NULL,
        dividend_interval INTEGER NOT NULL,
        project_rev VARCHAR(42) NOT NULL,
        platform_rev VARCHAR(42) NOT NULL,
        usdt_token VARCHAR(42) NOT NULL,
        start_time VARCHAR(78),
        is_active BOOLEAN DEFAULT false,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (token_address) REFERENCES tokens(address) ON DELETE CASCADE
      )
    `);
    
    // 创建交易记录表
    await client.query(`
      CREATE TABLE IF NOT EXISTS transactions (
        id SERIAL PRIMARY KEY,
        token_address VARCHAR(42) NOT NULL,
        transaction_hash VARCHAR(66) UNIQUE NOT NULL,
        transaction_type VARCHAR(50) NOT NULL,
        from_address VARCHAR(42),
        to_address VARCHAR(42),
        amount VARCHAR(78),
        usdt_amount VARCHAR(78),
        status VARCHAR(20) DEFAULT 'pending',
        block_number INTEGER,
        gas_used VARCHAR(78),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (token_address) REFERENCES tokens(address) ON DELETE CASCADE
      )
    `);
    
    // 创建分红记录表
    await client.query(`
      CREATE TABLE IF NOT EXISTS dividends (
        id SERIAL PRIMARY KEY,
        token_address VARCHAR(42) NOT NULL,
        round_number INTEGER NOT NULL,
        amount VARCHAR(78) NOT NULL,
        dividend_token VARCHAR(42),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (token_address) REFERENCES tokens(address) ON DELETE CASCADE
      )
    `);
    
    console.log('✅ Database tables initialized successfully');
    client.release();
  } catch (error) {
    console.error('❌ Error initializing database:', error);
    throw error;
  }
};

module.exports = {
  pool,
  initDatabase
};
